package com.syn.michat.util.Interceptor;

import com.alibaba.fastjson.JSON;
import com.syn.michat.constant.ErrorContants;
import com.syn.michat.model.ResponseEntity;
import com.syn.michat.pojo.User;
import com.syn.michat.util.ResponseErrorUtil;
import com.syn.michat.util.TokenUtil;
import com.syn.michat.util.exception.ClientException;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Token拦截器
 **/

public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");

        if (token == null) {
            ClientException exception = new ClientException(ErrorContants.ACCESSTOKEN_INVALID, "token不可为空", null);
            createResponse(exception, response);
            return true;
        }

        TokenUtil util = new TokenUtil();
        try {
            User user = util.verifyToken(token);
            request.setAttribute("user",user);
        } catch (ClientException e) {
            createResponse(e, response);
        }

        return true;
    }

    private void createResponse(ClientException exception, HttpServletResponse response) throws Exception {
        ResponseEntity entity = ResponseErrorUtil.convertException(exception);
        response.addHeader("Content-Type", "application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().println(JSON.toJSONString(entity));
        response.getWriter().close();
    }

}
